from datetime import datetime

from sqlalchemy import or_
from sqlalchemy.orm import joinedload, load_only, defer, Session

from api.models import Record, Car


def count_records(db, keyword=None):
    """查询记录数量"""
    query = db.query(Record).filter_by(is_deleted=False)
    if keyword:
        query = query.join(Car).filter(or_(
            Car.owner.contains(keyword),
            Car.carno.contains(keyword)
        ))
    return query.count()


def list_records(db, page, size, keyword=None):
    """分页查询违章记录"""
    query = db.query(Record).filter_by(is_deleted=False)
    if keyword:
        query = query.join(Car).filter(or_(
            Car.owner.contains(keyword),
            Car.carno.contains(keyword)
        ))
    return query.order_by(Record.makedate.desc())\
        .options(defer(Record.car_id), defer(Record.is_deleted),
                 defer(Record.deleted_time), defer(Record.updated_time))\
        .options(joinedload(Record.car).options(load_only(Car.carno, Car.owner)))\
        .offset((page - 1) * size).limit(size).all()


def handle_record(db, rno):
    """受理违章记录"""
    record = db.query(Record).filter_by(no=rno).first()
    if record:
        if not record.dealt:
            record.dealt = True
            record.updated_time = datetime.now()
        return True
    return False


def delete_record(db, rno) -> bool:
    """删除违章记录"""
    record = db.query(Record).filter_by(no=rno).first()
    if record and record.dealt:
        if not record.is_deleted:
            record.is_deleted = True
            record.deleted_time = datetime.now()
        return True
    return False
